package me.hekr.demo;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.igexin.sdk.PushManager;
import com.litesuits.common.assist.Toastor;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zhy.base.adapter.ViewHolder;
import com.zhy.base.adapter.abslistview.CommonAdapter;


import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import me.hekr.hekrsdk.action.HekrUser;
import me.hekr.hekrsdk.action.HekrUserAction;
import me.hekr.hekrsdk.bean.DeviceBean;
import me.hekr.hekrsdk.util.ConstantsUtil;
import me.hekr.hekrsdk.util.HekrCodeUtil;

public class DeviceListActivity extends AppCompatActivity {
    private HekrUserAction hekrUserAction;
    FloatingActionButton fab;
    private List<DeviceBean> lists;
    private ListView listView;
    private Toastor toastor;
    private SwipeRefreshLayout swipeRefreshLayout;
    private DisplayImageOptions options;
    private CommonAdapter adapter;

    private static final int CONFIG_WHAT = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_list);
        initView();
        initData();
        getDevices();
    }

    private void initView() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        listView = (ListView) findViewById(R.id.lv_devices);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.sw);
    }

    private void initData() {
        hekrUserAction = HekrUserAction.getInstance(this);
        toastor = new Toastor(this);
        lists = new ArrayList<>();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher)
                .showImageOnFail(R.mipmap.ic_launcher)
                .showImageForEmptyUri(R.mipmap.ic_launcher)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.RGB_565)//设置为RGB565比起默认的ARGB_8888要节省大量的内存
                .delayBeforeLoading(100)//载入图片前稍做延时可以提高整体滑动的流畅度
                .build();
        adapter = new CommonAdapter<DeviceBean>(this, R.layout.layout_devices_item, lists) {
            @Override
            public void convert(ViewHolder holder, final DeviceBean deviceBean) {
                TextView device_name = holder.getView(R.id.tv_dev_name);
                //TextView device_cid = holder.getView(R.id.tv_dev_cid);
                ImageView img_logo = holder.getView(R.id.img_icon);
                final TextView tv_online = holder.getView(R.id.tv_online);
                String cidName = deviceBean.getCidName();
                if (TextUtils.isEmpty(deviceBean.getDeviceName())) {
                    device_name.setText(cidName.substring(cidName.indexOf("/") + 1));
                } else {
                    device_name.setText(deviceBean.getDeviceName());
                }
                //holder.setText(R.id.tv_dev_cid, cidName.substring(cidName.indexOf("/") + 1));
                holder.setText(R.id.tv_dev_cid, cidName);
                ImageLoader.getInstance().displayImage(deviceBean.getLogo(), img_logo, options);
                if (deviceBean.isOnline()) {
                    tv_online.setText("在线");
                    img_logo.setBackgroundColor(ContextCompat.getColor(DeviceListActivity.this, R.color.devices_online));
                } else {
                    tv_online.setText("离线");
                    img_logo.setBackgroundColor(ContextCompat.getColor(DeviceListActivity.this, R.color.devices_offline));
                }

                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (deviceBean.isOnline()) {

                            final AlertDialog.Builder builder = new AlertDialog.Builder(DeviceListActivity.this);
                            builder.setTitle("控制方式");
                            builder.setItems(getResources().getStringArray(R.array.ctrl), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    switch (which) {
                                        case 0:
                                            Intent web= new Intent(DeviceListActivity.this, WebCtrlActivity.class);
                                            Bundle bundle=new Bundle();
                                            bundle.putSerializable("deviceBean",deviceBean);
                                            web.putExtras(bundle);
                                            startActivity(web);
                                            break;
                                        case 1:
                                            Intent i = new Intent(DeviceListActivity.this, DeviceCtrlActivity.class);
                                            i.putExtra("ctrlKey", deviceBean.getCtrlKey());
                                            i.putExtra("deviceTid", deviceBean.getDevTid());
                                            startActivity(i);
                                            break;
                                        case 2:
                                            break;
                                    }
                                }
                            });
                            builder.create().show();
                        } else {
                            toastor.showSingleLongToast("设备离线!");
                        }
                    }
                });
                holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        AlertDialog.Builder alert = new AlertDialog.Builder(DeviceListActivity.this)
                                .setTitle("删除或者解绑设备？")

                                .setMessage(deviceBean.getDeviceName() + "\n" + deviceBean.getDevTid())
                                .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        if (deviceBean.getOwnerUid().equals(hekrUserAction.getUserId())) {
                                            delete_device(deviceBean);
                                        } else {
                                            delete_oauth(deviceBean);
                                        }
                                    }
                                });
                        alert.create().show();
                        return true;
                    }
                });
            }
        };
        listView.setAdapter(adapter);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(DeviceListActivity.this, ConfigActivity.class), CONFIG_WHAT);

            }
        });
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getDevices();
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_device_list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this).setMessage("退出登录？").setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    startLogin();
                }
            });
            builder.create().show();

            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case CONFIG_WHAT:
                    getDevices();
                    break;

                default:
                    break;
            }
        }
    }

    /**
     * 获取设备列表
     */
    private void getDevices() {
        hekrUserAction.getDevices(0, 20, new HekrUser.GetDevicesListener() {
            @Override
            public void getDevicesSuccess(final List<DeviceBean> devicesLists) {
                lists.clear();
                lists.addAll(devicesLists);
                adapter.notifyDataSetChanged();
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void getDevicesFail(int errorCode) {
                if (errorCode == ConstantsUtil.ErrorCode.TOKEN_TIME_OUT) {
                    startLogin();
                }
                swipeRefreshLayout.setRefreshing(false);
                toastor.showSingleLongToast(HekrCodeUtil.errorCode2Msg(errorCode));
            }
        });
    }

    /**
     * 解除绑定
     */
    private void delete_device(DeviceBean deviceBean) {
        hekrUserAction.deleteDevice(deviceBean.getDevTid(), deviceBean.getBindKey(), new HekrUser.DeleteDeviceListener() {
            @Override
            public void deleteDeviceSuccess() {
                toastor.showSingleLongToast("删除成功");
                getDevices();
            }

            @Override
            public void deleteDeviceFail(int errorCode) {
                toastor.showSingleLongToast(HekrCodeUtil.errorCode2Msg(errorCode));
            }
        });
    }

    /**
     * 解除授权
     */
    private void delete_oauth(DeviceBean deviceBean) {
        hekrUserAction.cancelOAuth(deviceBean.getOwnerUid(), deviceBean.getCtrlKey(), hekrUserAction.getUserId(), deviceBean.getDevTid(), new HekrUser.CancelOAuthListener() {
            @Override
            public void CancelOAuthSuccess() {
                toastor.showSingleLongToast("删除成功");
                getDevices();
            }

            @Override
            public void CancelOauthFail(int errorCode) {
                toastor.showSingleLongToast(HekrCodeUtil.errorCode2Msg(errorCode));
            }
        });
    }

    /**
     * 强制退出登录！
     * context：应用上下文
     * alias：别名名称
     * isSelf：是否只对当前 cid 有效，如果是 true，只对当前cid做解绑；如果是 false，对所有绑定该别名的cid列表做解绑
     */
    private void startLogin() {
        PushManager.getInstance().unBindAlias(DeviceListActivity.this, hekrUserAction.getUserId(),true);
        hekrUserAction.userLogout();
        startActivity(new Intent(DeviceListActivity.this, LoginActivity.class));
        finish();
    }
}
